#include "BaseGame.h"
#include "resourceManager.h"

BaseGame::BaseGame()
{
}

BaseGame::~BaseGame()
{
}

bool BaseGame::onInit()
{
	CPlayerGUI::init();
	Level::smgr = Global::device->getSceneManager();
	level = Level::initialize();
	if ( level ) return true;
	return false;
}

void BaseGame::onUpdate()
{
	if( _state == STATE_GAME )
	{
		level->onUpdate();
		level->onAction();
		//Input::ClearBuffer();
	}
}

void BaseGame::onDestroy()
{
	Level::smgr = 0;
	Level::finalize();
	Global::device = 0;
	if ( InputManager ) delete InputManager;
	InputManager = 0;
}


bool BaseGame::StartUp()
{
	InputManager = new Input();
	_state = STATE_GAME_LOADING;
	return  true;
}

void BaseGame::Loop()
{
	bool firsttime = true;

	while(_state != STATE_GAME_END)
	{
		if (_state == STATE_MAIN_MENU_LOADING)
		{
			if (Global::deviceMenu)
				Global::deviceMenu->drop();
			Global::deviceMenu = createDevice(video::EDT_DIRECT3D8, dimension2d<s32>(800, 600), 32, false/*fullscreen*/, false, false, InputManager);//&receiver);
			Global::driver = Global::deviceMenu->getVideoDriver();
			ResourceManager::InitMenu();
			_state=STATE_MAIN_MENU;
		}
		else if (_state == STATE_GAME_LOADING)
		{	
			Global::device = createDevice(video::EDT_DIRECT3D8, dimension2d<s32>(800, 600), 32, false /*fullscreen*/, false, false, InputManager);//&receiver);
			Global::driver = Global::device->getVideoDriver();
			if (!onInit())
			{
				_state = STATE_GAME_END;
				return;
			}
			ResourceManager::InitGui();
			Input::Initialize();
			//ResourceManager::Load3dsModel("../media/cama01.3DS","../media/wood.jpg");
			_state = STATE_GAME;
		}
		else if (_state == STATE_MAIN_MENU)
		{
			while(Global::deviceMenu->run() && _state == STATE_MAIN_MENU)
			{
				Global::driver->beginScene(true, true, video::SColor(255, 113, 113, 133));
				ResourceManager::Menu.Draw();
				onUpdate();
				
				int opc = ResourceManager::Menu.GetOption();
				if(opc == 1){//PLAY GAME	
					_state = STATE_GAME_LOADING;		
					Global::deviceMenu->closeDevice();
				}				
				if(opc == 3){//PLAY GAME	
					_state = STATE_GAME_END;		
					Global::deviceMenu->closeDevice();
				}				
				Global::driver->endScene();
			}


		}//STATE MAIN MENU
		else if (_state == STATE_GAME)
		{
			while(Global::device->run())
			{
				Global::driver->beginScene(true, true, video::SColor(0xff000000));//(255, 113, 113, 133));
				Level::smgr->drawAll(); // draw the 3d scene
				Global::device->getGUIEnvironment()->drawAll();
				onUpdate();
				Global::driver->endScene();
			}
			_state=STATE_MAIN_MENU_LOADING;
		} // STATE GAME
	}//MAIN LOOP
}

void BaseGame::ShutDown()
{
	return onDestroy();
}
